package org.chenbingkang.boot.controller;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/excel")
public class ExcelController {

    @PostMapping("/upload")
    public void upload(MultipartFile file) {
        try {
            byte[] buffer = file.getBytes();
            SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(new ByteArrayInputStream(buffer)));
            Workbook workbook = sxssfWorkbook.getXSSFWorkbook();
            int sheetNum = workbook.getNumberOfSheets();
            for(int i=0;i<sheetNum;i++){
              Sheet sheet =  workbook.getSheetAt(i);
              int end = sheet.getLastRowNum();
              List<List<String>>  sheetList=new ArrayList<>();
              for(int j=0;j<=end;j++){
                  List<String> rowList=new ArrayList<>();
                  Row row=sheet.getRow(j);
                  int lastNum =  row.getLastCellNum();
                  for(int z=0;z<=lastNum;z++){
                      rowList.add(String.valueOf(row.getCell(z)));
                  }
                  sheetList.add(rowList);
              }
              System.out.println(sheet.getSheetName());
              System.out.println(sheetList);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
